package de.akabahn.ebd.control.auth;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Christian Schlehuber
 * @author Peter Eimann
 * @since 0.1
 * @version 0.2
 */
public abstract class AbstractAuthenticator {

	/**
	 * Method for authenticating a user to the system. The system responds to a
	 * correct set of user credentials with an UserAuthObject, which also
	 * contains the access level of the user
	 * 
	 * @param user
	 *            String containing the username of the user
	 * @param password
	 *            String containing the password of the user in clear text
	 * @return if the credentials are valid an UserAuthObject is returned. If
	 *         they are invalid null is returned, if both user and password are
	 *         null, a guest user with restricted access level is returned.
	 */
	public abstract UserAuthObject authenticateUser(String user, String password);

	/**
	 * Method to change the current password for an user.
	 * 
	 * @param user The user to change the password for
	 * @param oldPassword The old password
	 * @param newPassword The new password
	 * @return <code>true</code> - change was successul, <code>false</code> - change failed
	 */
	public abstract boolean changePassword(String user, String oldPassword, String newPassword);

	protected String md5hash(String password) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("SHA-256");
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}

		byte[] digest = messageDigest.digest(password.getBytes());
		StringBuilder sBuilder = new StringBuilder();
		for (byte d : digest) {
			sBuilder.append(Integer.toHexString(d & 0xFF));
		}

		return sBuilder.toString();
	}
}
